package cn.com.open.ms.ecgpaasdatarest.controller;

import cn.com.open.ms.ecgpaasdatarest.common.Result;
import cn.com.open.ms.ecgpaasdatarest.dynamicconfig.DynamicDataBaseSource;
import cn.com.open.ms.ecgpaasdatarest.service.BusinessService;
import cn.com.open.ms.ecgpaasdatarest.utils.GsonUtil;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description 数据动态查询接口
 * @author 奶茶
 * Created by on 2018/11/28 15:28.
 */
@RestController
@RequestMapping(value = "/api/v1/")
public class DataRestController {

    @Autowired
    private BusinessService businessService;

    /**
     * 根据业务名称动态查询数据
     * @param businessName 业务名称
     * @param tableName 表名称
     */
    @RequestMapping(value = "/{businessName}/{tableName}",method = RequestMethod.GET)
    public @ResponseBody
    ResponseEntity<String> dynamicDataSearch(@PathVariable(value = "businessName") String businessName, @PathVariable(value = "tableName") String tableName, @RequestHeader HttpHeaders headers) throws SQLException {
        String appKey = headers.getFirst("appKey");
        return new ResponseEntity<>(GsonUtil.toJson(new Result("",System.currentTimeMillis(),businessService.searchData(appKey, businessName, tableName))), HttpStatus.OK);
    }

    @RequestMapping(value = "/dataMonitor",method = RequestMethod.GET)
    public @ResponseBody ResponseEntity<String> dataMonitor(){
        Map<Object,Object> returnMap = new HashMap<>();
        Map<Object, Object> dataSourceMap = DynamicDataBaseSource.getInstance().getDataSourceMap();
        Iterator<Map.Entry<Object, Object>> iterator = dataSourceMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Object, Object> next = iterator.next();
            DruidDataSource value = (DruidDataSource) next.getValue();
            returnMap.put(next.getKey(),value.dump());
        }
        return new ResponseEntity<String>(GsonUtil.toJson(returnMap),HttpStatus.OK);
    }

}
